package com.baidu.game.textbudder;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baidu.game.service.IHappyBeanHistoryService;
import com.baidu.game.service.Userservice;
import com.baidu.game.entity.HappyBeanHistory;
import com.baidu.game.entity.RechargeOrder;
import com.baidu.game.service.IRechargeOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 充值订单
 */
@RestController
@CrossOrigin
public class RechargeOrderController {

    @Autowired
    private IRechargeOrderService rechargeOrderService;

    @Autowired
    private IHappyBeanHistoryService happyBeanHistoryService;

    @Autowired
    private Userservice userService;

    /**
     * 下单  欢乐豆 ： 充值金额 = 100 ： 1
     */
    @RequestMapping("/order/create")
    public String createOrder(Integer uid, double money){

        String orderid = UUID.randomUUID().toString();

        //double Integer -> BitDecimal
        BigDecimal moneyBD = BigDecimal.valueOf(money);
        BigDecimal numberBD = BigDecimal.valueOf(100);

        //创建订单对象
        RechargeOrder rechargeOrder = new RechargeOrder();
        rechargeOrder.setuId(uid);//下单用户id
        rechargeOrder.setMoney(moneyBD);//下单的金额
        rechargeOrder.setOrderId(orderid);//订单号
        rechargeOrder.setStatus(0);//未支付
        rechargeOrder.setCreateTime(new Date());//下单时间
        rechargeOrder.setBeanNumber(moneyBD.multiply(numberBD).intValue());//充值的欢乐豆数量 money * 100

        //添加订单
        rechargeOrderService.insertOrder(rechargeOrder);

        return orderid;
    }

    /**
     * 查询订单列表 根据用户id
     */
    @RequestMapping("/order/list")
    public List<RechargeOrder> queryList(Integer uid){
        return rechargeOrderService.queryRechargeOrderByUid(uid);
    }

    /**
     * 订单支付的接口
     */
    @RequestMapping("/order/pay")
    public void orderPay(String orderid, HttpServletResponse response) throws IOException {
        System.out.println("接收到支付的订单：" + orderid);

        //通过订单号 查询订单信息
        RechargeOrder order = rechargeOrderService.getByOrderId(orderid);

        //调用支付宝进行支付
        AlipayClient alipayClient =  new DefaultAlipayClient(
                "https://openapi.alipaydev.com/gateway.do",//沙箱环境的地址
                "2021000118679438",//APPID
                "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCHiBMtTdQSMEFCdoVfHflSEqx798s7hkhPrdTOEpjszYYqKbvDhouvVnnITu5+8ZY7I1sr0FAAzgSgwwdvN4UZG2rZ8dkkzIj99cyErXtjCs4NL/X2ndH9uk2fMgTqxv/Uy/Sm7Zc+ooEzLYd/Terh1uyDcQ3FCSFnlweGu6zlxGK+WOIWV4p6a5G7ozfqF5LfVRnP30cA73FXtKdqvFAV8ZrG39KBBTxhd/uTkxTN9yuiDvO3GgNzvCTC/vk4/MoHS0IPD977iqP790naYxOIcW6r1aT7YjBogOWcaD+J1S23g6re5Moo/xa48UyGJ2HRck4e34Uz1IyUnkm8yLH/AgMBAAECggEAXPHktNz64r5VAs9lB6X2pWJJB3sX1OpyDLKZjfkTBtKrf56/NYe/o68aNVRsGoJzFHtauuFQ/DxM0DLvlkXs8RrsXCqPT7009XTrnNGcHH/8bu7FLytsJyTstpAG7zsplzWHwjKN1lZ7ZC2FDrjQq7BI4ptVZhqs3e2lK7DpEWhtD7dU+n3jyDGDJwPXzWFnKstG4gTrkss/flXyC9rtFD3xRXyqOA6iPBALZ/EDOGXGOdvPgpAdChquZXlqb7HMr1WMrDTfyAGvOotkLUaLd4hOxLeNboMw8jg/jsShkVs9M9mB1zvE3hAkblXzkUt9WqA/UhsosC9uTrOJg1jZgQKBgQC8TxXviUJbyYhVlq6ESLp+O6zRqEvDbCTuW3pxYIpDez3ErTEC7F7gGL0917wtwEhaDumdqpZB5Voonij8MaOphlWt+zMcleGVKCzWKLHhYC23RDsNhYsGWhf9EZvS5KURdkgJ4v7y7PwoAxwqsiusAw7r861p+dL5XCNIeGfsfQKBgQC4QDXjaYYEpI3eCzc8yFE1A5v4D9BQrv/QH1/wZuXPF62EPbF0mbP44qUCIZE2GwdRtq1ZKCGDnexHyRvj0sjJ6x6cubhrSgm2LH8XDQpG2yRrx3FLgoE5+WVvYgl7vVtocwvADpgf0EK2lFOeGIXJ0jrFfkBxvaahW3dQD2otKwKBgQCXqxce3C3PYe3mCbw8HZvfqk7SeruzBbplJNbk1H3oRi4E5/2uvhTYZ/ScB9OwAcwEhThSXiAxqPnJ90FJhu2rz9/YhpevMWUEztv2DcbfoKiRkGoDxQipsAzcLr+Tx8bP3rW9CNCRdqDN1VttZB3aqIfvMU/+KFJtt3FPoHMLvQKBgEn81ubsP/nrTmDE5jiNRDbirSYOy5squuULRE5YM55WpsH8uB7XffLKqHJTomk0r1q73Z54xASDTReChaWVxjV3KgLLfWfwAjhaY+qQvPi5FUYGf9NPo67xHC9/EcnTvzoRQL2t3p6f1bpVk8JfnJHvztPxn9VMz/Xpsd6/YeajAoGAHjX+s9btsk/3izR1iezU9TJJ8D5bVGGLKd2DNJYjkHn9dCS9wiI3H0qgS2CmyEfk64jZTmkan2/cX9TOl7aoRkIpSkv3IdqJVr7U8cXgsaNYntIru8OCThYedQz1oS9bnCEat6myWS+0GO/i3WwvoxuiO6IOghcyJonVqCgLXSc=",//商户私钥
                "json",//数据格式  {key:value,key:value...}
                "utf-8",//编码集
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjI5A5Vn0bsyTMLhBc5XjdW3OvsknYIFqxu8bz3jKRcvifvgK2TC8W2n6ueGSbWaqX8UJpPJjEoMQOHY+H1P9cGkBUCerpkTBj0CifGlqZ6a7jWMQW8OkDHueTb/25QeL7tiAIzP574pKIRmMPzKWDtNvh2Cttd2Szy+8rVMZHOcuQbp8oOlTf1j+JSpf+sZvl7nbRGI45FVoSF7eAWUf+0nhbXzw+8Oa7w9jZqWGcLN9rKfKqhs1zBFmq9Mi+whqxStvWYUX4S9IMPwVfWFuiutF5GY9dAn21CpLnhqxTcWNWByC2OcasGnC6Bn9uj++ehcHPpxkg93MMKj+iv5LtwIDAQAB",//支付宝公钥
                "RSA2");//非对称加密算法 RSA RSA2

        //网页支付的请求对象
        AlipayTradePagePayRequest alipayRequest =  new  AlipayTradePagePayRequest(); //创建API对应的request
        alipayRequest.setReturnUrl( "http://www.baidu.com" );//同步请求
        alipayRequest.setNotifyUrl( "http://localhost:8080/pay/result" );//异步请求
        //支付的请求参数
        alipayRequest.setBizContent( "{"  +
                "    \"out_trade_no\":\"" + order.getOrderId() + "\","  +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\","  +
                "    \"total_amount\":" + order.getMoney().doubleValue() + ","  +
                "    \"subject\":\"欢乐豆" + order.getBeanNumber() + "个\""  +
                "  }" ); //填充业务参数
        String form= "" ;
        try  {
            //发送支付请求（调用支付宝服务器），返回一个支付的html页面
            form = alipayClient.pageExecute(alipayRequest).getBody();
        }  catch  (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType( "text/html;charset=utf-8");
        response.getWriter().write(form); //直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }

    /**
     * 支付交易查询接口
     */
    @RequestMapping("/pay/query")
    public int payResult(String orderid) throws AlipayApiException {
        System.out.println(orderid);
        //调用支付宝进行支付
        AlipayClient alipayClient =  new DefaultAlipayClient(
                "https://openapi.alipaydev.com/gateway.do",//沙箱环境的地址
                "2021000118679438",//APPID
                "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCHiBMtTdQSMEFCdoVfHflSEqx798s7hkhPrdTOEpjszYYqKbvDhouvVnnITu5+8ZY7I1sr0FAAzgSgwwdvN4UZG2rZ8dkkzIj99cyErXtjCs4NL/X2ndH9uk2fMgTqx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IfvMU/+KFJtt3FPoHMLvQKBgEn81ubsP/nrTmDE5jiNRDbirSYOy5squuULRE5YM55WpsH8uB7XffLKqHJTomk0r1q73Z54xASDTReChaWVxjV3KgLLfWfwAjhaY+qQvPi5FUYGf9NPo67xHC9/EcnTvzoRQL2t3p6f1bpVk8JfnJHvztPxn9VMz/Xpsd6/YeajAoGAHjX+s9btsk/3izR1iezU9TJJ8D5bVGGLKd2DNJYjkHn9dCS9wiI3H0qgS2CmyEfk64jZTmkan2/cX9TOl7aoRkIpSkv3IdqJVr7U8cXgsaNYntIru8OCThYedQz1oS9bnCEat6myWS+0GO/i3WwvoxuiO6IOghcyJonVqCgLXSc=",//商户私钥
                "json",//数据格式  {key:value,key:value...}
                "utf-8",//编码集
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjI5A5Vn0bsyTMLhBc5XjdW3OvsknYIFqxu8bz3jKRcvifvgK2TC8W2n6ueGSbWaqX8UJpPJjEoMQOHY+H1P9cGkBUCerpkTBj0CifGlqZ6a7jWMQW8OkDHueTb/25QeL7tiAIzP574pKIRmMPzKWDtNvh2Cttd2Szy+8rVMZHOcuQbp8oOlTf1j+JSpf+sZvl7nbRGI45FVoSF7eAWUf+0nhbXzw+8Oa7w9jZqWGcLN9rKfKqhs1zBFmq9Mi+whqxStvWYUX4S9IMPwVfWFuiutF5GY9dAn21CpLnhqxTcWNWByC2OcasGnC6Bn9uj++ehcHPpxkg93MMKj+iv5LtwIDAQAB",//支付宝公钥
                "RSA2");//非对称加密算法 RSA RSA2

        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderid);
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");

            //判断支付的结果
            String tradeStatus = response.getTradeStatus();
            if (tradeStatus.equals("TRADE_SUCCESS")) {
                //支付成功
                System.out.println("支付成功");

                //根据订单号 查询订单详情
                RechargeOrder order = rechargeOrderService.getByOrderId(orderid);

                //修改订单状态
                rechargeOrderService.updateOrderStatus(orderid, 1);

                //生成积分流水记录
                HappyBeanHistory happyBeanHistory = new HappyBeanHistory();
                happyBeanHistory.setuId(order.getuId());//欢乐豆流水所属用户
                happyBeanHistory.setBeanNumber(order.getBeanNumber());//欢乐豆的数量
                happyBeanHistory.setType(0);//增加
                happyBeanHistory.setSource(0);//欢乐豆来源 - 充值
                happyBeanHistory.setCreateTime(new Date());
                happyBeanHistoryService.insertHistory(happyBeanHistory);


                System.out.println(order.getBeanNumber()+"-----");
                //给用户设置欢乐豆
                int newHappyBean = userService.addHappyBean(order.getuId(), order.getBeanNumber());
                //将最新的欢乐豆数量返回给前端
                return newHappyBean;
            }
        } else {
            System.out.println("调用失败");
        }

        return -1;
    }
}